$(function () {

    /**
     * 首页判断，登录成功后进行判断
     */
    change();

    function change() {
        if (localStorage.getItem("phone")) {
            $(".change").empty();
            var html = "";
            html += `<span class="pull">已发布的商品</span>
      <img src="img/right.png">`;
            $(html).appendTo(".change")

        }
    }

    var GOODSINFO=ARR["goodsInfo"];
    /**
     * 如果传来有goodsinfo进行搜索
     *
     */
    if(GOODSINFO!=undefined){
        $.when( searchGoods(GOODSINFO, 6, 1)).done(function () {
            layui.use('laypage', function () {
                var laypage = layui.laypage;
                //执行一个laypage实例
                // console.log(COUNT)
                laypage.render({
                    elem: 'laypage',
                    count: SCOUNT,
                    limit: 6,
                    theme: "#5599FF",
                    layout: ['count', 'prev', 'page', 'next'],
                    jump: function (obj, first) {

                        if (!first) {
                            // console.log($(this).data('cid'))
                            searchGoods(GOODSINFO, 6, obj.curr);
                        }


                    }
                });
            });
        })
    }

    var flag = 1;
    $(".change img").click(function () {
        if (flag == 1) {
            flag = 0;
            $(".li").show();
        } else if (flag == 0) {
            flag = 1;
            $(".li").hide();
        }

    })

    /**
     * 退出登录，清除缓存
     */
    $(".nologin").click(function () {
        localStorage.clear();
        window.location.reload();
    })

    function getCateLog() {
        $.ajax({
            type: "post",
            url: URL + "/catelog/getCateLog",
            dataType: "json",
            success: function (data) {
                var data = data.data;
                var html = "";
                for (let i = 0; i < data.length; i++) {
                    html += `<li data-id="${data[i].id}">
                   <a>
                      <img src="${URL + data[i].img}">
                      <span>${data[i].name}</span>
                   </a>
                </li>`;

                }
                html += `        <p>关于我们|联系我们</p>
        <p>©2019 江苏大学校园二手市场</p>`
                $(html).appendTo(".mainLeft");
            }
        });
    }

    getCateLog();

    $(".login").click(function (e) {
        e.preventDefault();
        layer.open({
            type: 2,
            title: false,
            area: ['300px', '450px'],
            content: 'login.html' //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
        });
    });
    $(".regist").click(function (e) {
        e.preventDefault();
        layer.open({
            type: 2,
            title: false,
            area: ['300px', '450px'],
            content: 'regist.html' //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
        });
    });


    /**
     * 进入首页加载
     */
    getAllCateLog();

    function getAllCateLog() {
        $.ajax({
            type: "post",
            url: URL + "/goods/getAllCateLog",
            dataType: "json",
            success: function (data) {
                var data = data.data;
                var html = "";

                for (let i = 0; i < data.length; i++) {
                    html += `<div class="menu">
                         <h1>${data[i].catename}</h1>
                           <div class="box">`;
                    var goodses = data[i].goodses;
                    for (let j = 0; j < goodses.length; j++) {
                        html += ` <div class="card" data-catename="${data[i].catename}" data-id="${goodses[j].id}" data-name="${goodses[j].name}" data-price="${goodses[j].price}" data-realprice="${goodses[j].realPrice}" data-polishtime="${goodses[j].polishTime}" data-describle="${goodses[j].describle}" data-imgurl="${URL + "/" + goodses[j].imgUrl}">
                   <img src="${URL + "/" + goodses[j].imgUrl}">
                   <span class="price">${goodses[j].price}</span>
                   <p>${goodses[j].name}</p>
                   <span class="date">${goodses[j].polishTime}</span>
                   <span class="mark">江大市场</span>
               </div>`


                    }

                    html += `</div>
              </div>`;
                }
                $(html).appendTo(".content");


            }
        });
    }

    //返回顶部
    $(".goto").click(function () {
        $("html,body").animate({scrollTop: 0}, 500)
    });


    var COUNT = 0;
    $("body").on("click", ".mainLeft li", function () {
        var title = $(this).find("span").text();

        var ID = $(this).data("id");
        $.when(getGoodsById(title, ID, 6, 1)).done(function () {
            layui.use('laypage', function () {
                var laypage = layui.laypage;
                //执行一个laypage实例
                // console.log(COUNT)
                laypage.render({
                    elem: 'laypage',
                    count: COUNT,
                    limit: 6,
                    theme: "#5599FF",
                    layout: ['count', 'prev', 'page', 'next'],
                    jump: function (obj, first) {

                        if (!first) {
                            // console.log($(this).data('cid'))
                            getGoodsById(title, ID, 6, obj.curr);
                        }


                    }
                });
            });
        })


    })

    function getGoodsById(title, cateId, limit, page) {
        $(".content").empty();
        var defered = $.Deferred();
        $.ajax({
            type: "post",
            url: URL + "/goods/getGoodsById",
            data: {
                cateId: cateId,
                limit: limit,
                page: page
            },
            dataType: "json",
            success: function (data) {
                COUNT = data.count;
                var data = data.data;

                var html = "";
                console.log(data)
                html += `<div class="menu">
        <h1>${title}</h1>
          <div class="box">`;
                for (let i = 0; i < data.length; i++) {


                    html += ` <div class="card" data-id="${data[i].id}">
                   <img src="${URL + "/" + data[i].imgUrl}">
                   <span class="price">${data[i].price}</span>
                   <p>${data[i].name}</p>
                   <span class="date">${data[i].polishTime}</span>
                   <span class="mark">江大市场</span>
               </div>`


                }

                html += `</div>
        </div>`;
                $(html).appendTo(".content");


                defered.resolve();
            }
        });
        return defered.promise();
    }

    $("body").on("click", ".card", function () {
        var id = $(this).data("id");
        window.open("detail.html?id=" + id);
    })


    /**
     * 搜索功能
     */
    var SCOUNT = 0;
    $(".searchGoods").click(function () {
        var goodsInfo = $(".goodsInfo").val();
        if(goodsInfo=="" || goodsInfo==null){
            layer.msg("搜索不可为空！");
            return;
        }
        $.when( searchGoods(goodsInfo, 6, 1)).done(function () {
            layui.use('laypage', function () {
                var laypage = layui.laypage;
                //执行一个laypage实例
                // console.log(COUNT)
                laypage.render({
                    elem: 'laypage',
                    count: SCOUNT,
                    limit: 6,
                    theme: "#5599FF",
                    layout: ['count', 'prev', 'page', 'next'],
                    jump: function (obj, first) {

                        if (!first) {
                            // console.log($(this).data('cid'))
                            searchGoods(goodsInfo, 6, obj.curr);
                        }


                    }
                });
            });
        })


    })
    // $('.goodsInfo').bind('keypress', function (event) {
    //     if (event.keyCode == "13") {
    //         if(ev.keyCode==13) {
    //             var goodsInfo = $(".goodsInfo").val();
    //             if(goodsInfo=="" || goodsInfo==null){
    //                 layer.msg("搜索不可为空！");
    //                 return;
    //             }
    //             $.when( searchGoods(goodsInfo, 6, 1)).done(function () {
    //                 layui.use('laypage', function () {
    //                     var laypage = layui.laypage;
    //                     //执行一个laypage实例
    //                     // console.log(COUNT)
    //                     laypage.render({
    //                         elem: 'laypage',
    //                         count: SCOUNT,
    //                         limit: 6,
    //                         theme: "#5599FF",
    //                         layout: ['count', 'prev', 'page', 'next'],
    //                         jump: function (obj, first) {
    //
    //                             if (!first) {
    //                                 // console.log($(this).data('cid'))
    //                                 searchGoods(goodsInfo, 6, obj.curr);
    //                             }
    //
    //
    //                         }
    //                     });
    //                 });
    //             })
    //         }
    //     }
    // });

    function searchGoods(goodsInfo, limit, page) {
        $(".main").empty();
        var defered = $.Deferred();
        $.ajax({
            type: "post",
            url: URL + "/goods/searchGoods",
            data: {
                goodsInfo: goodsInfo,
                limit: limit,
                page: page
            },
            dataType: "json",
            success: function (data) {
                SCOUNT = data.count;
                var data = data.data;

                var html = "";
                console.log(data)
                html += `<div class="menu">
          <div class="box">`;
                for (let i = 0; i < data.length; i++) {


                    html += ` <div class="card" style="width: 25%" data-id="${data[i].id}">
                   <img src="${URL + "/" + data[i].imgUrl}">
                   <span class="price">${data[i].price}</span>
                   <p>${data[i].name}</p>
                   <span class="date">${data[i].startTime}</span>
                   <span class="mark">江大市场</span>
               </div>`


                }

                html += `</div>
        </div>`;
                $(html).appendTo(".main");
                defered.resolve();

            }

        });
        return defered.promise();
    }


    /**
     * 我要发布
     */
    $(".right").click(function () {
        if (!localStorage.getItem("phone")) {
            layer.msg("请先登录！");
            return;
        } else {
            window.open("user.html?push=1");
        }
    });

        /**
     * 已发布的商品
     * */
    $(".pull").click(function () {
        window.open("user.html?pull=1");
    })
})